

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class MainExchangeThread extends Thread {
	protected boolean dead;
	protected DatagramSocket socket;
	
	public MainExchangeThread(DatagramSocket socket) {
		super();
		this.dead = false;
		this.socket = socket;
	}
	
	@Override
	public void run() {
		while (true) {
			byte[] buffer = new byte[MainClass.BUF_SIZE];
			DatagramPacket message = new DatagramPacket(buffer, buffer.length);
			try {
				socket.receive(message);
			} catch (IOException e) {
				if (!socket.isClosed()) {
					System.err.println("[MainExchangeThread]Error when receiving the server message.");
					socket.close();
					e.printStackTrace();
				} else {
					break;
				}
			}
			if (dead) {
				break;
			}
			
			System.out.println("[SERVER]Probed from Server.");
			
			buffer[4] = 0x07;
			DatagramPacket response = new DatagramPacket(buffer, buffer.length, message.getAddress(), message.getPort());
			
			try {
				socket.send(response);
			} catch (IOException e) {
				if (!socket.isClosed()) {
					System.err.println("[MainExchangeThread]Error when sending the response to server.");
					socket.close();
					e.printStackTrace();
				} else {
					break;
				}
			}
		}
	}
	
	public void close() {
		this.dead = true;
	}
}
